package com.jyy.prefabricated.controller;

import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.entity.AccessoryFile;
import com.jyy.prefabricated.service.AccessoryFileService;
import com.jyy.prefabricated.service.BosService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * 附件表(AccessoryFile)表控制层
 *
 * @author makejava
 * @since 2021-05-14 10:16:53
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class AccessoryFileController {
    /**
     * 服务对象
     */
    @Resource
    private AccessoryFileService accessoryFileService;

    @Autowired
    private BosService bosService;

    @PostMapping("/accessory-file")
    public AjaxResult insert(@RequestParam(value = "file",required = false) MultipartFile file, @RequestParam(required = false) Integer type) throws IOException {
        AccessoryFile courseFile = new AccessoryFile();
        if(file != null){
            log.info("REST request to upload course file:{}",file.getOriginalFilename(),file.getSize());
            String url = "";
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String objectName = UUID.randomUUID().toString().replace("-","") + substring;
            url = bosService.putObject(file, objectName);
            courseFile.setName(originalFilename);
            courseFile.setSize((double)file.getSize());
            courseFile.setPath(url);
        } else {
            log.info("REST request to upload course file type:video");
        }
        AccessoryFile accessoryFile = accessoryFileService.insert(courseFile);
        AccessoryFile result = accessoryFileService.queryById(accessoryFile.getId());
        return AjaxResult.success(result);
    }


    @DeleteMapping("/accessory-file/{id}")
    public AjaxResult deleteById(@PathVariable Integer id){
        log.info("Rest request to delete course file by id:{}",id);
        boolean row = accessoryFileService.deleteById(id);
        if(row == true){

            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

}
